import React from 'react';
import { 
  Card, 
  Tabs, 
  Button, 
  Table, 
  Typography, 
  Space, 
  Spin, 
  Empty 
} from 'antd';
import { DownloadOutlined, CopyOutlined, CheckOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';

const { Title, Text } = Typography;

interface TranslationResultProps {
  result: {
    translations: Record<string, Record<string, string>>;
    outputFiles: Record<string, string>;
  };
  loading: boolean;
}

const TranslationResult: React.FC<TranslationResultProps> = ({ result, loading }) => {
  const [activeTab, setActiveTab] = React.useState<string>('');
  const [copied, setCopied] = React.useState<Record<string, boolean>>({});

  React.useEffect(() => {
    if (result && result.translations) {
      const firstLang = Object.keys(result.translations)[0];
      setActiveTab(firstLang);
    }
  }, [result]);

  if (loading) {
    return (
      <Card title="翻译结果" style={{ marginTop: 24, textAlign: 'center' }}>
        <Spin size="large" tip="翻译中，请稍候..." />
      </Card>
    );
  }

  if (!result || !result.translations || Object.keys(result.translations).length === 0) {
    return (
      <Card title="翻译结果" style={{ marginTop: 24 }}>
        <Empty description="暂无翻译结果" />
      </Card>
    );
  }

  const handleCopyJson = (lang: string) => {
    const jsonContent = JSON.stringify(result.translations[lang], null, 2);
    navigator.clipboard.writeText(jsonContent).then(() => {
      setCopied({ ...copied, [lang]: true });
      setTimeout(() => {
        setCopied({ ...copied, [lang]: false });
      }, 2000);
    });
  };

  const columns = [
    {
      title: '键名',
      dataIndex: 'key',
      key: 'key',
      width: '30%',
    },
    {
      title: '翻译内容',
      dataIndex: 'value',
      key: 'value',
      width: '70%',
    },
  ];

  const items: TabsProps['items'] = Object.keys(result.translations).map(lang => {
    const data = Object.entries(result.translations[lang]).map(([key, value]) => ({
      key,
      value,
    }));

    return {
      key: lang,
      label: getLanguageName(lang),
      children: (
        <div>
          <Space style={{ marginBottom: 16 }}>
            <Button 
              type="primary" 
              icon={<DownloadOutlined />}
              onClick={() => downloadJson(lang, result.translations[lang])}
            >
              下载JSON文件
            </Button>
            <Button 
              icon={copied[lang] ? <CheckOutlined /> : <CopyOutlined />}
              onClick={() => handleCopyJson(lang)}
            >
              {copied[lang] ? '已复制' : '复制JSON'}
            </Button>
          </Space>
          
          <Table 
            columns={columns} 
            dataSource={data} 
            rowKey="key"
            pagination={{ pageSize: 10 }}
            size="middle"
          />
        </div>
      ),
    };
  });

  // 批量下载所有JSON文件
  const handleDownloadAllJson = () => {
    // 使用JSZip需要安装依赖，这里使用简单方法：连续下载所有文件
    Object.keys(result.translations).forEach((lang, index) => {
      // 添加延迟，避免浏览器阻止多个下载
      setTimeout(() => {
        downloadJson(lang, result.translations[lang]);
      }, index * 300);
    });
  };

  return (
    <Card title="翻译结果" style={{ marginTop: 24 }}>
      <div style={{ marginBottom: 16, textAlign: 'right' }}>
        <Button 
          type="primary" 
          icon={<DownloadOutlined />} 
          onClick={handleDownloadAllJson}
        >
          批量下载所有JSON文件
        </Button>
      </div>
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={items}
        type="card"
      />
    </Card>
  );
};

// 获取语言名称
function getLanguageName(code: string): string {
  const languageMap: Record<string, string> = {
    'zh': '中文',
    'en': '英文',
    'ja': '日文',
    'ko': '韩文',
    'fr': '法文',
    'de': '德文',
    'es': '西班牙文',
    'ru': '俄文',
  };
  
  return languageMap[code] || code;
}

// 下载JSON文件
function downloadJson(lang: string, data: Record<string, string>): void {
  const jsonContent = JSON.stringify(data, null, 2);
  const blob = new Blob([jsonContent], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  a.download = `${lang}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

export default TranslationResult;